import { UI_Listen, RedDot_Key, UI_Layer } from '../../config/ui_def';
import scrollOpt from '../base/scrollOptimize'
import util from '../tool/util'
import { Sdk_Platform, WX_AD_CONFIG, VIVO_AD_CONFIG, OPPO_AD_CONFIG, Ad_Type } from '../../frame/constants';
cc.Class({
    extends: scrollOpt,

    properties: {
        evetyDayBtn: cc.Node,
        achieveBtn: cc.Node,
        time_lab: cc.Label,
        bottomNode: cc.Node,
    },



    initPage() {
        if (!he.pool.getPool('taskItem')) {
            he.pool.createPoolSync('taskItem', 5, cc.Prefab, 'uimod/taskItem')
        }
    },

    updatePage() {
        console.log('sosososos')
        this.scrollInit()
        this.aniGrp = []
        this.taskListIndex = 0
        this.isDayTask = false
        this.creatDayTask()
        this.getTime()
        this.scheduleTime()
        this.scroll.scrollToTop()
        gg.eventManager.on('mission', this.listenClient, this)
        this.adSwitch(true)
        gg.redManager.updateRedDot(RedDot_Key.TASK, false)
        // this.scheduleServer()
        // this.openListen()
    },

    closeUI() {
        this.adSwitch(false)
        this.clearAni()
        this.clearAllItem()
        this.closeListen()
        this.stopSchedule()
        this.stopTimeSch()
        this.node.targetOff(this)
        for (let j = (this.bottomNode.children.length); j > 0; j--) {
            this.bottomNode.children[j - 1].getComponent('scrollAd').clearItem()
            he.pool.putElement('scrollAd', this.bottomNode.children[j - 1])
        }
        gg.redManager.updateRedDot(RedDot_Key.TASK)
    },
    // 
    adSwitch(status) {
        if (status) {
            switch (common.sdk_env) {
                case Sdk_Platform.WECHAT:
                    if (!common.showAd) return
                    he.ad.getTdAdJson(WX_AD_CONFIG.tmIcon[8], this.bottomSet.bind(this))
                    he.ad.interstitialShow()
                    break
                case Sdk_Platform.VIVO:
                    // this.bottomNode.name = VIVO_AD_CONFIG.bannerId[0]
                    // he.ad.changeBanner(status, this.bottomNode)
                    // he.ad.interstitialShow()
                    let guideList1 = he.local.getJson('guideList', 'user')
                    if (!guideList1[6]) {
                        return
                    }
                    let num3 = Math.ceil(Math.random() * 10)//20 的几率弹出
                    if (num3 < 2) {
                        gg.uiManager.addPage(UI_Layer.Click, {
                            name: 'randomCardPage',
                            cover: true,
                        })
                        break
                    }
                    break
                case Sdk_Platform.UC:
                    let guideList5 = he.local.getJson('guideList', 'user')
                    if (!guideList5[6]) {
                        return
                    }
                    let num4 = Math.ceil(Math.random() * 10)//20 的几率弹出
                    if (num4 < 2) {
                        gg.uiManager.addPage(UI_Layer.Click, {
                            name: 'randomCardPage',
                            cover: true,
                        })
                        break
                    }
                    he.ad.showInterstitialAd()
                    break
                case Sdk_Platform.OPPO:
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'chayeAdFakeOPPO',
                        isShowAd: true,
                        isShowBanner: false,
                        adIndex: 9,
                        position: cc.Vec2(0, -470)
                    })
                    let num = Math.ceil(Math.random() * 10)//20 的几率弹出
                    if (num < 2) {
                        gg.uiManager.addPage(UI_Layer.Click, {
                            name: 'randomCardPage',
                            cover: true,
                        })
                        break
                    }
                    break
                case Sdk_Platform.HUAWEI:
                    let guideList8 = he.local.getJson('guideList', 'user')
                    if (!guideList8[6]) {
                        return
                    }
                    if (gg.uiManager.getPage(UI_Layer.Msg, 'hwAdPage')) {
                        gg.uiManager.closePage(UI_Layer.Msg, 'hwAdPage')
                    }
                    gg.uiManager.addPage(UI_Layer.Msg, {
                        name: 'hwAdPage',
                        cover: false,
                        isShowAd: true,
                        adType: Ad_Type.INSERT,
                        position: 0
                    })

                    break
                default:
                    let guideList2 = he.local.getJson('guideList', 'user')
                    if (!guideList2[6]) {
                        return
                    }
                    let num2 = Math.ceil(Math.random() * 10)//20 的几率弹出
                    if (num2 < 2) {
                        gg.uiManager.addPage(UI_Layer.Click, {
                            name: 'randomCardPage',
                            cover: true,
                        })
                        break
                    }
                    break

            }
        } else {
            //  关掉广告
            switch (common.sdk_env) {
                case Sdk_Platform.WECHAT:
                    break
                case Sdk_Platform.VIVO:
                    // this.bottomNode.name = VIVO_AD_CONFIG.bannerId[0]
                    // he.ad.changeBanner(status, this.bottomNode)

                    break
                case Sdk_Platform.OPPO:
                    gg.uiManager.closePage(UI_Layer.Msg, 'chayeAdFakeOPPO')
                    // this.bottomNode.name = OPPO_AD_CONFIG.bannerId[0]
                    // he.ad.changeBanner(status, this.bottomNode)
                    break
                case Sdk_Platform.UC:
                    he.ad.closeBanner()
                    break
                case Sdk_Platform.HUAWEI:
                    if (gg.uiManager.getPage(UI_Layer.Msg, 'hwAdPage')) {
                        gg.uiManager.closePage(UI_Layer.Msg, 'hwAdPage')
                    }
                    break
            }
        }
    },
    closeServer() {
        this.uiBase.closePage()
    },
    listenClient(code) {
        switch (code.type) {
            case UI_Listen.TASK_UPDATE:
                //本来准备用来更新所有的任务
                this.isDayTask = false
                this.creatDayTask()
                break
            case UI_Listen.TASK_CLOSE:
                this.closeServer()
                break
        }
    },

    bottomSet(config) {
        if (config.isOpen) {
            let pre = he.pool.getElement('scrollAd')
            pre.parent = this.bottomNode
            pre.getComponent('scrollAd').init(config.creatives, 1, true)
        }
    },

    //清理所有的任务
    clearAllItem() {
        for (let i = (this.content.children.length); i > 0; i--) {
            he.pool.putElement('taskItem', this.content.children[i - 1])
        }
    },
    clearAni() {
        if (this.aniGrp && this.aniGrp.length != 0) {
            for (let i = 0; i < this.aniGrp.length; i++) {
                this.aniGrp[i].stop()
            }
        }
        this.aniGrp = []
    },


    creatDayTask() {
        if (this.isDayTask) return
        this.closeUI()
        let task = he.local.getJson('task', 'user')
        if (task && task.length > 0) {
            task = this.taskSort(task)
            let adNum = this.randomNum(2, 4)
            task.splice(adNum, 0, { isAd: true })
            if (task && task.length > 0) {
                for (let i = 0; i < task.length; i++) {
                    let pre = he.pool.getElement('taskItem')
                    pre.parent = this.content
                    pre.opacity = 255
                    if (task[i].isAd) {
                        pre.getComponent('taskItem').taskItemInit(task[i], true)
                    } else {
                        pre.getComponent('taskItem').taskItemInit(task[i])
                    }
                    pre.x += 800
                }
            }
            this.isDayTask = true
            this.btnChange(1)
            this.taskListIndex = 0
            this.scheduleServer()
            this.openListen()
        }

    },

    //范围内的随机数
    randomNum(minNum, maxNum) {
        switch (arguments.length) {
            case 1:
                return parseInt(Math.random() * minNum + 1, 10);
                break;
            case 2:
                return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
                break;
            default:
                return 0;
                break;
        }
    },


    taskSort(task) {
        if (task && task.length > 0) {
            let canGet = []
            let haveGet = []
            let onGet = []
            for (let i = 0; i < task.length; i++) {
                if (task[i].isGet) {
                    haveGet.push(task[i])
                }
                if (!task[i].isGet && task[i].num >= task[i].need) {
                    canGet.push(task[i])
                }
                if (task[i].num < task[i].need) {
                    onGet.push(task[i])
                }
            }
            if (onGet.length > 0) {
                for (let item in onGet) {
                    onGet[item].bili = onGet[item].num / onGet[item].need
                }
            }
            onGet = util.sortObj(onGet, 'desc', 'bili')
            return canGet.concat(onGet, haveGet)
        }
    },
    creatAchieveTask() {
        if (!this.isDayTask) return
        this.closeUI()

        let task = he.local.getJson('task', 'user')
        if (task && task.length > 0) {
            for (let i = 0; i < task.length; i++) {
                let pre = he.pool.getElement('taskItem')
                pre.parent = this.content
                pre.getComponent('taskItem').taskItemInit(task[i])
                pre.x += 800
            }
        }
        this.isDayTask = false
        this.btnChange(2)
        this.taskListIndex = 0
        this.scheduleServer()
        this.openListen()
    },


    btnChange(type) {
        if (type == 1) {
            this.evetyDayBtn.getChildByName('bg').getComponent(cc.Sprite).spriteFrame = he.load.get('taskPage', cc.SpriteAtlas, 'plist').getSpriteFrame(`btn_renwu_1`)
            this.achieveBtn.getChildByName('bg').getComponent(cc.Sprite).spriteFrame = he.load.get('taskPage', cc.SpriteAtlas, 'plist').getSpriteFrame(`btn_renwu_2`)
        } else {
            this.evetyDayBtn.getChildByName('bg').getComponent(cc.Sprite).spriteFrame = he.load.get('taskPage', cc.SpriteAtlas, 'plist').getSpriteFrame(`btn_renwu_2`)
            this.achieveBtn.getChildByName('bg').getComponent(cc.Sprite).spriteFrame = he.load.get('taskPage', cc.SpriteAtlas, 'plist').getSpriteFrame(`btn_renwu_1`)
        }
    },

    scheduleServer() {
        this.schedule(this.aniServer, 0.1, this.content.children.length, 0)
    },

    stopSchedule() {
        this.unschedule(this.aniServer)
    },

    aniServer() {
        if (!this.content.children) return
        if (this.taskListIndex >= this.content.children.length) {
            this.stopSchedule()
            return
        }
        this.aniGrp[this.taskListIndex] = cc.tween(this.content.children[this.taskListIndex])
            .to(0.3, { x: 0 })
            .start()
        this.taskListIndex += 1
    },


    scheduleTime() {
        this.schedule(this.getTime, 1, 1440 * 60, 0)
    },

    stopTimeSch() {
        this.unschedule(this.getTime)
    },

    getTime() {
        let hour = new Date().getHours()
        let min = new Date().getMinutes()
        let miao = new Date().getSeconds()
        this.time_lab.string = `${util.prefixInteger((24 - hour - 1), 2)}:${util.prefixInteger((60 - min - 1), 2)}:${util.prefixInteger((60 - miao), 2)}`
    },

});
